package com.atguigu.fruit.controller;

import com.atguigu.fruit.pojo.Fruit;
import com.atguigu.fruit.service.FruitService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/fruits")
public class FruitController {

    @Autowired
    private FruitService fruitService;


        @GetMapping("/")
    public  String index(){
        return "index";
    }
    @PostMapping
    public Result insertSelective(@RequestBody Fruit fruit) {
        boolean flag = fruitService.insertSelective(fruit);
        return  new Result(flag ? Code.SAVE_OK:Code.SAVE_ERR,flag);
    }

    @PutMapping
    public Result update(@RequestBody Fruit fruit) {
        boolean flag = fruitService.updateSelectiveById(fruit);
        return new Result(flag ? Code.UPDATE_OK:Code.UPDATE_ERR,flag);

    }

    @DeleteMapping("/{fid}")
    public Result delete(@PathVariable Integer fid) {
        boolean flag = fruitService.deleteByFid(fid);

        return new  Result(flag ? Code.DELETE_OK:Code.DELETE_ERR,flag);

    }

    @GetMapping("/{fid}")
    public Result getById(@PathVariable Integer fid) {
        List<Fruit> fruitList = fruitService.selectByFid(fid);

        Integer code = fruitList != null ? Code.GET_OK : Code.GET_ERR;

        String msg = fruitList != null ? "" : "数据查询失败，请重试！";
        return new Result(code,  fruitList, msg);
    }

    @GetMapping
    public Result getAll() {

        List<Fruit> fruitList = fruitService.searchAll();
        Integer code = fruitList != null ? Code.GET_OK : Code.GET_ERR;
        String msg = fruitList != null ? "" : "数据查询失败，请重试！";
        return new Result(code, fruitList, msg);
    }

    @GetMapping("{currentPage}/{pageSize}")
    public IPage<Fruit> getPage(@PathVariable int currentPage, @PathVariable int pageSize){
        return fruitService.getPage(currentPage,pageSize, null);
    }
}
